const renderNums = function(num,unit){
    num += '';
    var numIndex = num.indexOf('.');
    var intStr = '',pointStr = '',floatStr = '',unitStr='';
    var intArr,floatArr;
    intArr = (num.slice(0,numIndex)).split('');
    intArr.map((item)=>{
        intStr += '<div class="num_item num">'+item+'</div>'
    })
    if(numIndex > -1){
        floatArr = (num.slice(numIndex+1)).split('')
        pointStr = '<div class="num_item point">.</div>';
        floatArr.map((item)=>{
            floatStr += '<div class="num_item num">'+item+'</div>'
        })
    }else{
        pointStr = '';
        floatStr = ''
    }
    unitStr = unit?'<div class="num_item unit">'+unit+'</div>':''
    // $(id).html(intStr + pointStr + floatStr)
    return intStr + pointStr + floatStr + unitStr

}
 //时间戳转换为正常时间格式
 const timeNew=function () {
  var dt = new Date(), // 获取时间
    Hous = dt.getHours(), //获取 小时 (0-23)
    Min = dt.getMinutes(), //获取 分(0-59)
    Sec = dt.getSeconds()
  Hous < 10 ? (Hous = '0' + Hous) : ''
  Min < 10 ? (Min = '0' + Min) : ''
  Sec < 10 ? (Sec = '0' + Sec) : ''
  let newTime = Hous + ':' + Min + ':' + Sec
  return newTime
}
//时间返回格式
const dataNew=function () {
  var dt = new Date(), // 获取时间
    Y = dt.getFullYear(), //获取 年 (四位)
    Mont = dt.getMonth() + 1, //获取 月 (0-11,0代表1月)
    Day = dt.getDate() //获取 日 （1-31）
  Mont < 10 ? (Mont = '0' + Mont) : ''
  Day < 10 ? (Day = '0' + Day) : ''
  let newTime = Y + '.' + Mont + '.' + Day
  let datelist = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  return {
    week: datelist[new Date(newTime).getDay()],
    day: newTime
  }
}

const dateFormat = function(dateStr,split,isTime){
    //时间处理dateFormat(20220415,-)
	split = split||'-';
	if(dateStr){
		var date = new Date(dateStr);
	    var y = date.getFullYear();      
	    var m = date.getMonth() + 1;      
	    m = m < 10 ? ('0' + m) : m;      
	    var d = date.getDate();      
	    d = d < 10 ? ('0' + d) : d;      
	    var h = date.getHours();    
	    h = h < 10 ? ('0' + h) : h;    
	    var minute = date.getMinutes();    
	    var second = date.getSeconds();    
	    minute = minute < 10 ? ('0' + minute) : minute;      
		second = second < 10 ? ('0' + second) : second;   
		if(isTime){
			return y + split + m + split + d+' '+h+':'+minute+':'+second;    
		}else{
			return y + split + m + split + d;    
		}
	    
	}else{
		return dateStr
  }
}
const adaptePX = function (px){
    var vHeight = window.screen.height;
    // console.log(window.height , document.documentElement.clientHeight , document.body.clientHeight,window.screen.height)
    return px * vHeight / 1080;
}
const numToThousand = function (num){
    if(num>=1000){
        var arr = (num+'').split('').reverse(),newArr=[];
        arr.forEach((item,i)=>{
            newArr.push(item)
            if((i+1) % 3 == 0 && i!= arr.length-1){
                newArr.push(',');
            }
        })
        return newArr.reverse().join('');

    }else{
        return num;
    }
}
const hasProps = function(obj,propName,defaultValue){
    return obj.hasOwnProperty(propName)?obj[propName]:defaultValue;
}
const setDefaultValue = function(obj,propName,defaultValue){

}

//函数节流
const throttle = (fn, timer) => {
    if (timer == null || timer == undefined) {
      timer = 1000
    }
    let lastTime = null
    // 返回新的函数
    return function () {
      let nowTime = +new Date()
      if (nowTime - lastTime > timer || !lastTime) {
        fn.apply(this, arguments) //将this和参数传给原函数
        lastTime = nowTime
      }
    }
  }
  
  /**
   * 防抖函数
   * @param {function} func 方法
   * @param {Number} wait 该时长内仅触发1次
   * Returns a function, that, as long as it continues to be invoked, will not
   * be triggered. The function will be called after it stops being called for
   * N milliseconds. If `immediate` is passed, trigger the function on the
   * leading edge, instead of the trailing.
   */
  const debounce = (func, wait, immediate) => {
    var timeout
    var asyncHandler
    return async function () {
      var context = this
      var args = arguments
      var callNow = immediate && !timeout
      clearTimeout(timeout)
      asyncHandler = new Promise(resolve => {
        timeout = setTimeout(() => {
          timeout = null
          if (!immediate) {
            resolve(func.apply(context, args))
          }
        }, wait)
        return callNow ? Promise.resolve(func.apply(context, args)) : asyncHandler
      })
    }
  }
  
  // 判断是否是iphoneX
  const isIphonex = () => {
    if (typeof window !== 'undefined' && window) {
      return /iphone/gi.test(window.navigator.userAgent) && window.screen.height >= 812
    }
    return false
  }
  
  const isMobile = mobile => {
    const mobileRegExp = /^1[3456789]\d{9}$/
    return mobileRegExp.test(mobile)
  }
  
  //字符串转换为时间戳
  const getDateTimeStamp = dateStr => {
    return Date.parse(dateStr.replace(/-/gi, '/'))
  }
  
  // 时间转换为x天前 x周前等等
  const getDateDiff = dateTimeStamp => {
    dateTimeStamp = getDateTimeStamp(dateTimeStamp)
    var minute = 1000 * 60
    var hour = minute * 60
    var day = hour * 24
    // var halfamonth = day * 15
    var month = day * 30
    var now = new Date().getTime()
    var diffValue = now - dateTimeStamp
    if (diffValue < 0) {
      return
    }
    var monthC = diffValue / month
    var weekC = diffValue / (7 * day)
    var dayC = diffValue / day
    var hourC = diffValue / hour
    var minC = diffValue / minute
    let result
    if (monthC >= 1) {
      result = '' + parseInt(monthC) + '月前'
    } else if (weekC >= 1) {
      result = '' + parseInt(weekC) + '周前'
    } else if (dayC >= 1) {
      result = '' + parseInt(dayC) + '天前'
    } else if (hourC >= 1) {
      result = '' + parseInt(hourC) + '小时前'
    } else if (minC >= 1) {
      result = '' + parseInt(minC) + '分钟前'
    } else result = '刚刚'
    return result
  }
  
  // 判断是否是数组
  function isArray(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]'
  }
  
  // 深拷贝
  const deepClone = obj => {
    let newObj
    // 判断复制的目标是不是数组
    if (isArray(obj)) {
      newObj = []
    } else if (typeof obj === 'object') {
      newObj = {}
    } else {
      newObj = obj
    }
    if (typeof obj === 'object') {
      for (let item in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, item)) {
          if (obj[item] && typeof obj[item] === 'object') {
            newObj[item] = deepClone(obj[item])
          } else {
            newObj[item] = obj[item]
          }
        }
      }
    }
    return newObj
  }
  
  	//获取设备类型
   const GetNavigator= function () {
        var nav = navigator.userAgent.toLowerCase(), //用户设备参数
            type = 'h5';
        if (nav.indexOf('micromessenger') > -1) {
            type = 'h5_weixin'; //微信
        } else if (nav.indexOf('dingtalk') > -1) {
            type = 'h5_dingtalk'; //钉钉
        } else if (nav.indexOf('nebulasdk') > -1 && nav.indexOf('taurusapp') > -1) {
            type = 'h5_nebulasdk'; //浙政钉
        } else if (nav.indexOf('alipayclient') > -1 && nav.indexOf('miniprogram') < 0) {
            type = 'h5_alipay'; //支付宝
        } else if (nav.indexOf('qq') > -1) {
            type = 'h5_qq'; //支付宝
        } else if (nav.indexOf('dtdreamweb') > -1 || (nav.indexOf('miniprogram') > -1 && nav.indexOf('alipay') > -
                1)) {
            type = 'h5_hanweb'; //浙里办
        }
        //访问来源 h5/pc
        that.setData('PROVIDER_SOURCE', nav.indexOf('mobile') < 0 ? 'pc' : 'h5');
        return type;
    }

    //获取设备型号
 const  getBrowser= function () {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
        var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
        var isIE11 = (/Trident\/7\./).test(userAgent); //判断是否IE11浏览器
        var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !
            isOpera; //判断是否IE浏览器
        var isEdge = userAgent.indexOf("Edge") > -1; //判断是否IE的Edge浏览器
        var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器
        var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -
            1; //判断是否Safari浏览器
        var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器

        var StringPhoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i" +
            "|windows (phone|ce)|blackberry" +
            "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp" +
            "|laystation portable)|nokia|fennec|htc[-_]" +
            "|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
        var StringTableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser" +
            "|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";

        var ua = userAgent.toLocaleLowerCase(),
            isIphone = ua.match(StringPhoneReg),
            isTable = ua.match(StringTableReg),
            isMobile = isIphone || isTable;

        //是否移动端
        if (isMobile) {
            if (!!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
                return 'ios';
            } else {
                //防止安卓设备软键盘遮挡输入框
                function resizeFun() {
                    if (document.activeElement.tagName == "INPUT" || document.activeElement.tagName ==
                        "TEXTAREA") {
                        window.setTimeout(function() {
                            document.activeElement.scrollIntoViewIfNeeded();
                        }, 0);
                    }
                }
                window.removeEventListener('resize', resizeFun)
                window.addEventListener("resize", resizeFun);
                return 'android';
            }
        } else {
            if (isIE) {
                var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
                reIE.test(userAgent);
                var fIEVersion = parseFloat(RegExp["$1"]);
                if (fIEVersion == 7) {
                    return "IE7";
                } else if (fIEVersion == 8) {
                    return "IE8";
                } else if (fIEVersion == 9) {
                    return "IE9";
                } else if (fIEVersion == 10) {
                    return "IE10";
                } else if (fIEVersion == 11) {
                    return "IE11";
                } else {
                    return "IE";
                } //IE版本过低
            }
            if (isIE11) {
                return "IE11";
            }
            if (isOpera) {
                return "Opera";
            }
            if (isEdge) {
                return "Edge";
            }
            if (isFF) {
                return "FF";
            }
            if (isSafari) {
                return "Safari";
            }
            if (isChrome) {
                return "Chrome";
            }
        }
    }
  // 后端返回的相对路径导致本地无法显示图片，故判断本地开发环境，加上所在域名进行图片url处理
  const addDomain = url => {
    return process.env.NODE_ENV === 'development' ? `https://wh.risenoa.com:23015${url}` : url
  }
//根据搜索关键字，对应的文字变色。
  const getRedColor=function(keyValue, str) {
      var reg = new RegExp(keyValue.trim(), 'gmi')
      return str.replace(reg, `<span class="text-red">${keyValue}</span>`)
    }
export {renderNums,adaptePX,numToThousand,dateFormat,getBrowser,GetNavigator};